package org.nuplay;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import com.illposed.osc.OSCMessage;

public class NuPlayConnector {
	private DatagramSocket client_socket;
	private DatagramPacket packet;
	private boolean below_threshold;
	private Integer channel;

	public NuPlayConnector(InetAddress address, Integer in_channel) {
		this.channel = in_channel;
		try {
			client_socket = new DatagramSocket();
			client_socket.connect(address, 3333);
			packet = new DatagramPacket(new byte[255], 255);
			below_threshold = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		System.out.println("closed");
		client_socket.close();
		client_socket = null;
	}
	
	public boolean isBelowThreshold() {
		return below_threshold;
	}

	public void sendOn(int volume) {
		below_threshold = false;
		OSCMessage osc_message = new OSCMessage();
		osc_message.setAddress("/nuplay/channel_" + this.channel);
		osc_message.addArgument(new String("audio"));
		osc_message.addArgument(new Integer(1));
		osc_message.addArgument(new Integer(volume));
		packet.setData(osc_message.getByteArray());
		System.out.println("/nuplay/channel_" + this.channel + " on " + volume);
		try {
			client_socket.send(packet);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void sendOff(int volume) {
		below_threshold = true;
		OSCMessage osc_message = new OSCMessage();
		osc_message.setAddress("/nuplay/channel_" + this.channel);
		osc_message.addArgument(new String("audio"));
		osc_message.addArgument(new Integer(0));
		osc_message.addArgument(new Integer(volume));
		osc_message.setAddress("/nuplay/channel_" + this.channel);
		packet.setData(osc_message.getByteArray());
		System.out.println("/nuplay/channel_" + this.channel + " off " + volume);
		try {
			client_socket.send(packet);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
